import React, { useEffect } from 'react';
import logo from './logo.svg';
import './App.css';
import { Container, ListGroup, ListGroupItem } from 'react-bootstrap';
import { Link, useNavigate } from 'react-router-dom';
import AppSetting from './store/AppSetting';
import {AccessTokenRespResult} from './model/AccessTokenResp';
import appSetting from './store/AppSetting';

function App() {
  const navigate = useNavigate();
  
  const refreshToken = (onSuccess:any)=> {
    const token = localStorage.getItem("token")||""
    AppSetting.updateAccessToken(token);
    if(!appSetting.accessToken || appSetting.accessToken.length === 0){
      let url = "/wxproxy/cgi-bin/token?grant_type=client_credential&appid=wx3ea51e40d566d4a0&secret=cd59ef384f1473b85494e8fd04ffec26";
      fetch(url,{
        method:"GET",
      }).then((res)=>res.json()).then((jsonResp)=>{
        let tokenResp = jsonResp as unknown as AccessTokenRespResult;
        AppSetting.updateAccessToken(tokenResp.access_token);
        localStorage.setItem("token",tokenResp.access_token);
        onSuccess && onSuccess()
      })  
    }else{
      console.log("current token: "+appSetting.accessToken)
      onSuccess && onSuccess();
    }
  }

  useEffect(()=>{
    refreshToken(null);
  },[])

  return (
    <div className="App">
      <h1>首页</h1>
      <ListGroup>
       <ListGroupItem>
            <Link to={"/debug.html"}>Debug</Link>
        </ListGroupItem>
        <ListGroupItem onClick={()=>{
            localStorage.setItem("token","");
            AppSetting.updateAccessToken("");
            refreshToken(()=>{
              alert("success");
            });
        }}>
            <Container className='btn btn-primary'>刷新token</Container>
        </ListGroupItem>
        <ListGroupItem onClick={()=>{
            refreshToken(()=>{
              fetch(`/apiclear_quota?access_token=${appSetting.accessToken}`).then(()=>{
                alert("success")
              }).catch((err)=>{
                alert(JSON.stringify(err));
              })
            });
        }}>
          <Container className='btn btn-primary'>清除quota</Container>
        </ListGroupItem>
        <ListGroupItem onClick={()=>{
          navigate("/menu")
        }}>
          <Container className='btn btn-primary'>菜单管理</Container>
        </ListGroupItem>
        <ListGroupItem onClick={()=>{
          navigate("/users/manage")
        }}>
          <Container className='btn btn-primary'>用户管理</Container>
        </ListGroupItem>
        <ListGroupItem onClick={()=>{
          navigate("/material")
        }}>
          <Container className='btn btn-primary'>素材管理</Container>
        </ListGroupItem>
      </ListGroup>
    </div>
  );
}

export default App;
